<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <div class="app-space-between">
        <div class="app-space-between-left">
          <el-form-item label="上级分类:" prop="goodsTypeParentid">
            <el-select v-model="queryParams.goodsTypeParentid" clearable placeholder="请输入上级分类" @change="handleQuery">
              <el-option v-for="(item,index) in parentData" :key="index" :label="item.goodsTypeParentName"
                :value="item.goodsTypeId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类:" prop="goodsTypeName">
            <el-input v-model="queryParams.goodsTypeName" placeholder="请输入商品分类" clearable @clear="handleQuery"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </div>
        <div class="app-space-between-right">
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
            <el-button size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleAdd" v-hasPermi="['system:post:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" :disabled="single" @click="handleUpdate">编辑</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataTable" @selection-change="handleSelectionChange"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}" v-if="refreshTable" row-key="goodsTypeId"
      :default-expand-all="isExpandAll">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品分类" align="center" prop="goodsTypeParentName" />
      <el-table-column label="上级分类" align="center" prop="goodsTypeParentid">
        <template slot-scope="scope">
          <div>{{scope.row | goodsTypeParentidName(this)}}</div>
        </template>
      </el-table-column>
      <el-table-column label="排序号" align="center" prop="sort" />
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品分类:" prop="goodsTypeName">
          <el-input v-model="form.goodsTypeName" placeholder="请输入商品分类" />
        </el-form-item>
        <el-form-item label="上级分类:" prop="goodsTypeParentid">
          <treeselect v-model="form.goodsTypeParentid" :options="[{goodsTypeId:'',goodsTypeParentName:'根目录'},...dataTable]"
            :normalizer="normalizer" :show-count="true" placeholder="选择上级菜单" />
        </el-form-item>
        <el-form-item label="排序号:" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" :max="999999"></el-input-number>
        </el-form-item>
        <el-form-item label="分类图片:" prop="goodsTypePic">
          <image-upload :isShowTip="false" v-model="form.goodsTypePic" :limit="1"></image-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{form.goodsTypeId?'保 存':'确 定'}}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    goodsType,
    goodsTypeList,
    goodsTypeDetele,
    goodsTypeDetails,
    goodsTypeEdit
  } from "@/api/shopping/column"
  import Treeselect from "@riophae/vue-treeselect"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css"
  let _this
  export default {
    name: "ShoppingContent",
    dicts: ['sys_normal_disable'],
    components: {
      Treeselect
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        refreshTable: '',
        isExpandAll: true,
        refreshTable: true,
        dataTable: [],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 岗位表格数据
        postList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          goodsTypeParentid: undefined,
          goodsTypeName: undefined
        },
        parentData:[],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          goodsTypeName: [{
            required: true,
            message: "请输入商品分类",
            trigger: "blur"
          }],
          goodsTypeParentid: [{
            required: false,
            message: "请选择上级分类",
            trigger: "blur"
          }],
          sort: [{
            required: true,
            message: "请输入排序号",
            trigger: "blur"
          }]
        }
      };
    },
    filters: {
      goodsTypeParentidName(options) {
        for (let i in _this.postList) {
          if (options.goodsTypeParentid == _this.postList[i].goodsTypeId) return _this.postList[i].goodsTypeParentName
        }
      }
    },
    beforeCreate() {
      _this = this
    },
    created() {
      this.getList();
      goodsTypeList({}).then(res=>{
          this.parentData = res.rows
      });
    },
    methods: {
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.goodsTypeId,
          label: node.goodsTypeParentName,
          children: node.children
        };
      },
      getList() {
        this.loading = true;
        goodsTypeList(this.queryParams).then(response => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.dataTable = this.handleTree(response.rows, 'goodsTypeId', 'goodsTypeParentid')
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      // 表单重置
      reset() {
        this.form = {
          goodsTypeName: '',
          goodsTypePic: '',
          sort: 0,
          goodsTypeParentid: ''
        };
        this.resetForm("form");
      },
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        console.log(selection)
        this.ids = selection.map(item => item.goodsTypeId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加分类";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const postId = row.goodsTypeId || this.ids
        goodsTypeDetails(postId).then(response => {
          // response.data.status = `${response.data.status}`
          this.form = response.data;
          console.log(response.data)
          this.open = true;
          this.title = "修改分类";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.goodsTypeId != undefined) {
              goodsTypeEdit(this.form).then(response => {
                this.$modal.msgSuccess("编辑成功");
                this.open = false;
                this.getList();
              })
            } else {
              goodsType(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        let postIds = row.goodsTypeIds || this.ids;
        if (Array.isArray(postIds)) postIds = postIds.toString()

        this.$modal.confirm('是否确认删除岗位编号为"' + postIds + '"的数据项？').then(function() {
          return goodsTypeDetele(postIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/post/export', {
          ...this.queryParams
        }, `post_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
